#include "localimageview.h"

#include <cstring>
#include <cstdio>
using namespace std;

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
using namespace cv;

LocalImageView::LocalImageView(QWidget *parent) :
    ImageView(parent)
{
    this->m_device = -1;
    this->m_source = "";
    this->m_last_timer_state = false;
    QObject::connect(&this->m_timer, SIGNAL(timeout()), this, SLOT(grab()));

}

void LocalImageView::changeVideoSource(QString source){
    if(source != this->m_source){
        if(source.startsWith("video")){
            this->m_device = atoi(source.right(source.length() - strlen("video")).toStdString().c_str());
            this->m_source = source;
            this->m_timer.setInterval(30);
            this->m_capture.open(this->m_device);
            this->m_timer.start();
        }else if(source.startsWith("/")){//just for linux
            this->m_device = -1;
            this->m_source = source;
            this->m_timer.setInterval(30);
            this->m_capture.open(this->m_source.toStdString());
            this->m_timer.start();
        }else{
            this->m_device = -1;
            this->m_source = "";
            this->m_timer.stop();
        }
    }
}

void LocalImageView::stopGrab(){
    if(this->m_timer.isActive()){
        this->m_last_timer_state = true;
        this->m_timer.stop();
    }else{
        this->m_last_timer_state = false;
    }
}

void LocalImageView::continueGrab(){
    if(this->m_last_timer_state){
        this->m_timer.setInterval(30);
        this->m_timer.start();
        this->m_last_timer_state = false;
    }
}

void LocalImageView::grab(){
    if(m_img_mutex.tryLock()){
        this->m_capture >> this->m_img;
        if(!m_img.data){
            this->m_timer.stop();
            this->m_capture.release();
            return;
        }
        this->showImage(this->m_img);
        m_img_mutex.unlock();
    }
}






